<template>
  <div class="project-arragement">
    <el-divider content-position="left">抽取内容</el-divider>
    <el-select size="small" v-if="isJq" v-model="queryParams.deptId1" placeholder="请选择集群" filterable :loading="dept1Loading" :disabled="listLoading || isSuppDraw" @change="changeDeptId1" style="margin-right: 10px">
      <el-option v-for="item in dept1List" :key="item.fid" :label="item.deptName" :value="item.fid" />
    </el-select>
    <el-select size="small" v-model="queryParams.bsNodeId" placeholder="请选择检查类型" :disabled="listLoading || isSuppDraw" @change="changeBsNode">
      <el-option v-for="item in bsNodeList" :key="item.bsNodeId" :label="item.businessType" :value="item.bsNodeId">
        <span>{{ item.businessType }}</span>
      </el-option>
    </el-select>
    <el-divider content-position="left">项目范围</el-divider>
    <div style="margin-bottom: 10px;">
      <el-button size="mini" @click="allSelect">全选</el-button>
      <el-button size="mini" @click="invertSelection">反选</el-button>
      <el-dropdown @command="onReloadType" :disabled="listLoading">
        <el-button size="mini" icon="el-icon-refresh" :loading="listLoading" style="margin: 0 10px">
          {{ isLastTime ? '加载最近一次' : '条件加载' }}
          <i class="el-icon-arrow-down el-icon--right" />
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="condition" style="font-size: 12px">条件加载</el-dropdown-item>
          <el-dropdown-item command="lastTime" style="font-size: 12px">加载最近一次</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <!--<el-button size="mini" @click="getList" :loading="listLoading">重新加载</el-button>-->
      <el-button type="warning" size="mini" icon="el-icon-delete" @click="handlePoorRemove" :disabled="multipleSelection.length === 0" v-if="showBtns.removePrj">移除范围项目</el-button>
      <el-button type="primary" size="mini" icon="el-icon-plus" @click="openSelectProList" :disabled="firstTimeComing || listLoading" v-if="showBtns.addPrj">新增范围项目</el-button>
      <!--<el-button type="primary" size="mini" @click="handleStatus(multipleSelection)" :disabled="multipleSelection.length === 0">安排</el-button>-->
      <el-input placeholder="请输入名称" size="mini" v-model="searchParams.name" clearable style="width:260px;margin: 0 10px;" @change="projectNameChange">
        <el-select v-model="searchParams.key" slot="prepend" placeholder="请选择" style="width: 100px;">
          <el-option v-for="dept in deptList" :key="dept.key" :label="dept.name" :value="dept.key" />
        </el-select>
      </el-input>
      <el-button type="primary" size="mini" icon="el-icon-search" @click="projectNameChange">搜索</el-button>
    </div>
    <div class="table-wrap">
      <!--
      <div class="first-load-btns" v-if="firstTimeComing">
        <div class="btns">
          <el-button class="btn btn1" type="primary" size="mini" @click="onReloadType('condition')">条件加载</el-button>
          <el-button class="btn btn2" type="success" size="mini" @click="onReloadType('lastTime')">加载最近一次</el-button>
        </div>
        <div class="desc">
          <div style="border-bottom: 1px solid #dcdfe6">根据{{ showBusinessType }}的进入条件与退出条件加载项目抽取范围</div>
          <div>加载最近一次{{ showBusinessType }}抽取范围数据</div>
        </div>
      </div>
      -->
      <poor-process ref="poorProcessRef" @onReloadType="onReloadType" />
      <el-table
        ref="multipleTable"
        size="mini"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        height="250px"
        @selection-change="handleSelectionChange"
      >
        <span slot="empty">{{ firstTimeComing || listLoading ? '' : '暂无数据' }}</span>
        <el-table-column
          type="selection"
          min-width="55"
          :selectable="row => row.status > 0"
        />
        <!--<el-table-column-->
        <!--type="selection"-->
        <!--min-width="55"-->
        <!--/>-->
        <el-table-column
          label="集群"
          min-width="120"
        >
          <template slot-scope="scope">{{ scope.row.deptName1 }}</template>
        </el-table-column>
        <el-table-column
          prop="deptName2"
          label="事业部"
          min-width="120"
        />
        <el-table-column
          prop="deptName3"
          label="城市公司"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="项目"
          min-width="100"
          show-overflow-tooltip
        >
          <template slot-scope="{row}">{{ row.displayName }}</template>
        </el-table-column>
        <!--<el-table-column label="状态" align="center" width="80">
          <div slot-scope="{ row }" @click="toggleIsEnable(row)" style="display: inline-block; cursor: pointer">
            <el-switch class="g-switch-in" v-model="row.isEnable" active-text="启用" inactive-text="停用" :width="50" style="pointer-events: none" />
          </div>
        </el-table-column>-->
        <el-table-column label="状态" align="center" min-width="80">
          <dict-tag slot-scope="{ row }" :options="proRangeStatusList" :value="row.status" />
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" min-width="100">
          <template slot-scope="{ row }">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleStatus(row)" v-if="row.status === 1 || row.status === 2">选择添加</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" :loading="row.removeLoading" @click="handleDelete(row)" v-if="showBtns.removePrjForever && row.status === 1">永久删除</el-button>
            <!--<el-button size="mini" type="text" icon="el-icon-delete" @click.stop="removeManuallyAdded(row)" v-else-if="showBtns.addPrj && row.status === 2">移除范围项目</el-button>-->
            <el-button size="mini" type="text" icon="el-icon-refresh-left" @click.stop="statusCancelToNormal(row)" v-else-if="showBtns.removePrj && row.status === -1">恢复</el-button>
            <el-button size="mini" type="text" icon="el-icon-refresh-left" :loading="row.removeLoading" @click.stop="handleUndelete(row)" v-else-if="showBtns.removePrjForever && row.status === -2">恢复</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-divider content-position="left">已选列表</el-divider>
    <el-table
      :data="selectedList"
      tooltip-effect="dark"
      size="mini"
      style="width: 100%"
      height="180px"
    >
      <el-table-column
        label="集群"
        min-width="120"
      >
        <template slot-scope="scope">{{ scope.row.deptName1 }}</template>
      </el-table-column>
      <el-table-column
        prop="deptName2"
        label="事业部"
        min-width="120"
      />
      <el-table-column
        prop="deptName3"
        label="城市公司"
        min-width="100"
        show-overflow-tooltip
      />
      <el-table-column
        label="项目"
        min-width="100"
        show-overflow-tooltip
      >
        <template slot-scope="{row}">{{ row.displayName }}</template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="100">
        <template slot-scope="{ $index }">
          <el-button size="mini" type="text" icon="el-icon-delete" @click="cancelSelected($index)">取消</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align: right;margin-top: 10px;">
      <el-button type="success" size="mini" icon="el-icon-check" :loading="saveLoading" @click="saveData" :disabled="selectedList.length === 0">确认</el-button>
      <el-button :disabled="listLoading" size="mini" @click="onCancel">取 消</el-button>
    </div>
    <SelectProList ref="SelectProList" @selected="onSelectProList" />
  </div>
</template>

<script>
import auth from '@/plugins/auth'
import { listProPoor, getHisRange, foreverDel, savePeRecord, recoverForeverDel, getDept1List } from '@/api/cqPe/peRecord'
import SelectProList from './SelectProList'
import { listBsNode } from '@/api/cqPe/bsNode'
import { proRangeStatusList, rdcTypeAuthMap, handleableGenType } from './common'
import { v4 as uuidv4} from 'uuid'
import poorProcess from './poorProcess'
import { CQ_EVAL_RDC_TYPE as RDC_TYPE } from '@/utils/baseData'
export default {
  name: 'ProjectArrangement',
  components: {SelectProList, poorProcess},
  dicts: ['cq_eval_rdc_type'],
  data() {
    return {
      firstTimeComing: false,
      peRecordId: '', // 有值为补抽
      firAss: '', // gc, ds
      rdcType: '',
      belongSystem: '',
      proRangeStatusList,
      listLoading: false,
      saveLoading: false,
      tableData: [],
      queryParams: {
        busCacheId: '',
        bsNodeId: '',
        deptId1: '',
        needFilter: 1
      },
      searchParams: {
        key: 'displayName',
        name: ''
      },
      originalList: [],
      reloadType: 'condition', // 重载方式
      multipleSelection: [],
      selectedList: [],
      deptList: [
        { key: 'deptName1', name: '集群' },
        { key: 'deptName2', name: '事业部' },
        { key: 'deptName3', name: '城市公司' },
        { key: 'displayName', name: '项目' }
      ],
      saveParams: {
        bsNodeId: '',
        needRandom: 0
      },
      bsNodeList: [],
      busCacheId: '',
      dept1List: [], // 集群
      dept1Loading: false
    }
  },
  computed: {
    showBtns() {
      // 操作按钮权限
      const firAss = this.firAss
      const rdcType = rdcTypeAuthMap[this.rdcType] || ''
      const permCode = `cqPe:peRecord:${firAss}:${rdcType}`

      const addPrj = auth.hasPermi(`${permCode}:addPrj`)
      const removePrj = auth.hasPermi(`${permCode}:removePrj`)
      const removePrjForever = auth.hasPermi(`${permCode}:removePrjForever`)

      return { addPrj, removePrj, removePrjForever }
    },
    isSuppDraw() {
      // 是否补抽
      return !!this.peRecordId
    },
    isJq() {
      // 是否集群
      return this.rdcType === RDC_TYPE.DEPT2
    },
    isLastTime() {
      // 是否加载上一次
      return this.reloadType === 'lastTime'
    },
    showBusinessType() {
      // 根据 bsNodeId 获取检查类型
      const id = this.queryParams.bsNodeId
      const list = this.bsNodeList || []
      if (!id || !list.length) return ''

      const item = list.find(i => i.bsNodeId === id)
      return item?.businessType || ''
    }
  },
  methods: {
    // 组件使用必传字段 firAss, rdcType 和 bsNodeId
    open(obj) {
      this.firstTimeComing = true
      this.tableData = []
      this.selectedList = []
      this.reloadType = 'condition'
      this.peRecordId = obj.peRecordId || ''
      this.firAss = obj.firAss
      this.rdcType = obj.rdcType
      this.belongSystem = obj.belongSystem || ''
      this.queryParams.bsNodeId = obj.bsNodeId
      this.queryParams.deptId1 = obj.deptId1
      this.getBsNodeList()

      // 先从页面取列表，解决弱网下列表未加载时显示 id
      this.dept1List = obj.dept1List || []
      if (this.isJq) this.getDept1List()

      this.getList()
    },
    changeBsNode(bsNodeId) {
      const { deptId1 } = this.queryParams
      const item = this.bsNodeList.find(i => i.bsNodeId === bsNodeId)
      this.$emit('changeBsNode', { ...item, deptId1 })
    },
    async getBsNodeList() {
      const { rdcType, belongSystem } = this
      const opt = { pageNum: 1, pageSize: 9999, isEnable: true, rdcType, belongSystem }
      const res = await listBsNode(opt).catch(() => false)
      if (res === false) return

      let data = res.rows || []
      // 只取 检查,抽查
      data = data.filter(i => handleableGenType.includes(i.generationType))
      this.bsNodeList = data
    },
    async onCancel() {
      const res1 = await this.$confirm('确认关闭？', '提示', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return
      this.$emit('cancel')
    },
    async saveData() {
      const params = {bsNodeId: this.queryParams.bsNodeId, saveProlist: this.selectedList, projectList: this.originalList}
      if (this.peRecordId) params.peRecordId = this.peRecordId

      this.saveLoading = true
      savePeRecord(params).then(res => {
        if (res.code === 200) {
          this.$emit('saveSuccess', res.data) // 保存成功
        }
      }).finally(() => {
        this.saveLoading = false
      }).catch(() => false)
    },
    onReloadType(command) {
      this.reloadType = command || 'condition'
      this.getList()

      // 加载失败，重新获取
      if (!this.bsNodeList.length) this.getBsNodeList()
      if (this.isJq && !this.dept1List.length) this.getDept1List()
    },
    async getDept1List() {
      this.dept1Loading = true
      const res = await getDept1List().catch(() => false)
      this.dept1Loading = false
      if (res === false) return

      const data = res.data || []
      this.dept1List = data
    },
    changeDeptId1() {
      this.getList()
    },
    async getList() {
      this.firstTimeComing = false
      let error = false
      let sysErrMsg = ''
      this.busCacheId = uuidv4()
      this.queryParams.busCacheId = this.busCacheId

      // 集群检查才传 deptId1
      const opt = { ...this.queryParams }
      if (!this.isJq) delete opt.deptId1

      this.$refs.poorProcessRef.open(this.busCacheId)
      this.listLoading = true
      const reqApi = this.isLastTime ? getHisRange : listProPoor
      const res = await reqApi(opt).catch(err => {
        if (err instanceof Object && err.message) {
          sysErrMsg = err.message
        } else if (typeof err === 'string') {
          sysErrMsg = err
        }
        return false
      })
      this.listLoading = false
      if (!res) {
        error = true
      }
      this.$refs.poorProcessRef.close(error, sysErrMsg)
      const data = (this.isLastTime ? res.data : res.rows) || []
      data.map(i => {
        i.removeLoading = false
      })
      this.originalList = JSON.parse(JSON.stringify(data))
      this.projectNameChange()
    },
    openSelectProList() {
      this.$refs.SelectProList.open({
        bsNodeId: this.queryParams.bsNodeId,
        deptId1: this.isJq ? this.queryParams.deptId1 : '',
        list: this.originalList
      })
    },
    onSelectProList(selected) {
      const { originalList } = this
      const proIdMap = originalList.reduce((o, i) => !void (o[i.uniqueId] = 1) && o, {})
      const list2 = selected.filter(i => !proIdMap[i.uniqueId])
      list2.forEach(item => {
        item.status = 2
      })
      this.originalList = this.originalList.concat(list2)
      this.projectNameChange()
      this.msgInfo(`新增 ${list2.length} 项`)
    },
    allSelect() {
      this.$refs.multipleTable.toggleAllSelection()
    },
    invertSelection() {
      this.tableData.forEach(row => {
        this.$refs.multipleTable.toggleRowSelection(row)
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    projectNameChange() {
      this.tableData = this.originalList.filter(item => {
        if (this.selectedList.some(selected => selected.uniqueId === item.uniqueId)) {
          return false
        }
        if (this.searchParams.key && this.searchParams.name) {
          if (item[this.searchParams.key]) {
            return item[this.searchParams.key].includes(this.searchParams.name)
          } else {
            return false
          }
        } else {
          return true
        }
      })
    },
    // 安排
    handleStatus(obj) {
      if (obj) {
        if (obj instanceof Array) {
          obj.forEach(item => {
            if (!this.selectedList.some(selected => selected.uniqueId === item.uniqueId)) {
              this.selectedList.push({...item})
            }
          })
        } else if (typeof obj === 'object') {
          if (!this.selectedList.some(selected => selected.uniqueId === obj.uniqueId)) {
            this.selectedList.push({...obj})
          }
        }
      }
      this.projectNameChange()
    },
    // 移除
    handlePoorRemove() {
      this.$confirm(`移除后的项目将不再本次抽取范围, 是否继续?`, '移除范围项目', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.tableData.forEach(row => {
          if (this.multipleSelection.some(item => item.uniqueId === row.uniqueId)) {
            row.status = -1
          }
        })
        this.originalList.forEach(row => {
          if (this.multipleSelection.some(item => item.uniqueId === row.uniqueId)) {
            row.status = -1
          }
        })
        this.sortList()
      }).catch(() => {

      })
    },
    async handleDelete(row) {
      this.$confirm(`永久删除后项目将不再抽取检查,永久删除项目：${row.displayName}, 是否继续?`, '永久删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { bsNodeId } = this.queryParams
        const opt = { ...row, businessType: bsNodeId, status: -2 }
        delete opt.removeLoading

        row.removeLoading = true
        const res = await foreverDel(opt).catch(() => false)
        row.removeLoading = false
        if (!res) return
        row.status = -2
        this.$refs.multipleTable.toggleRowSelection(row, false)
      }).catch(() => {

      })
    },
    cancelSelected(index) {
      this.selectedList.splice(index, 1)
      this.projectNameChange()
    },
    sortList() {
      this.$refs.multipleTable.clearSelection()
      this.originalList.sort((a, b) => b.status - a.status)
      this.tableData.sort((a, b) => b.status - a.status)
    },
    async handleUndelete(item) {
      // 状态 -2 => 1
      if (item.removeLoading) return
      const res1 = await this.$confirm(`确认恢复：${item.displayName}？`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      const { bsNodeId } = this.queryParams
      const opt = { ...item, businessType: bsNodeId, status: 1 }
      delete opt.removeLoading

      item.removeLoading = true
      const res = await recoverForeverDel(opt).catch(() => false)
      item.removeLoading = false
      if (res === false) return

      this.msgSuccess('已恢复')
      item.status = 1
      this.sortList()
    },
    async statusCancelToNormal(item) {
      // 状态 -1 => 1
      const res1 = await this.$confirm(`确认恢复：${item.displayName}？`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      item.status = 1
      this.sortList()
    },
    removeManuallyAdded(item) {
      // 移除手动添加的
      const { originalList, tableData } = this
      const index = originalList.find(i => i.uniqueId === item.uniqueId)
      originalList.splice(index, 1)
      const index2 = tableData.find(i => i.uniqueId === item.uniqueId)
      tableData.splice(index2, 1)
    }
  }
}
</script>
<style scoped lang="scss">
  .table-wrap {
    position: relative;
  }
  .project-arragement {
    position: relative;
  }
  .first-load-btns {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 11;
    display: flex;
    justify-content: center;
    align-items: center;
    backdrop-filter: blur(2px);
    .btn {
      display: block;
      width: 100px;
      height: 50px;
      padding: 0;
      &:hover {
        transform: scale(1.1);
        box-shadow: 1px 5px 5px rgba(0, 0, 0, 0.1);
      }
    }
    .btn1 {
      border-radius: 50px 50px 0 0;
      border-bottom: 0;
    }
    .btn2 {
      border-radius: 0 0 50px 50px;
      border-top: 0;
      margin-left: unset;
    }
    .desc {
      margin-left: 10px;
      font-size: 12px;
      line-height: 50px;
    }
  }
</style>
